/* $Id: SubmissionsServlet.java 133 2011-08-26 12:01:00Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.servlets;

import java.util.Date;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import alt.djudge.frontend.server.datatypes.AbstractEntry;
import alt.djudge.frontend.server.datatypes.ContestEntry;
import alt.djudge.frontend.server.datatypes.ContestProblemEntry;
import alt.djudge.frontend.server.datatypes.ContestUserEntry;
import alt.djudge.frontend.server.datatypes.LanguageEntry;
import alt.djudge.frontend.server.datatypes.SubmissionEntry;
import alt.djudge.frontend.server.datatypes.UserEntry;
import alt.djudge.frontend.server.models.ContestProblemsModel;
import alt.djudge.frontend.server.models.ContestUsersModel;
import alt.djudge.frontend.server.models.ContestsModel;
import alt.djudge.frontend.server.models.CoreInterface;
import alt.djudge.frontend.server.models.LanguagesModel;
import alt.djudge.frontend.server.models.SubmissionsModel;
import alt.djudge.frontend.server.models.UsersModel;
import alt.djudge.frontend.server.utils.Linker;


@SuppressWarnings("unused")
public class SubmissionsServlet extends AbstractDataServlet
{
	private static final long serialVersionUID = 1L;	

	@Override
	protected CoreInterface<? extends AbstractEntry> getModel()
	{
		return SubmissionsModel.getCore();
	}
	
	@Override
	protected void processAction(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		/*
        // TODO: a lot of checks
        if ("submit".equals(action))
        {
        	UserEntry user = UsersModel.getCurrentUser(req);
        	
            if (user == null)
            {
            	setRedirect("login.jsp");
            	setMessage("You must log in to submit solutions");
            	return;
            }
            
            if (user.isAdmin())
            {
            	try
            	{
            		user = UsersModel.getUser(Long.parseLong(req.getParameter("userId")));
            	}
            	catch (Exception e) {
					// TODO: handle exception
				}
            }
            
            String problemIdString = req.getParameter("problemId");
            String fFirstTestOnly = req.getParameter("fFirstTestOnly");
            String languageIdString = req.getParameter("languageId");
            Long problemId = Long.parseLong(problemIdString);
            Long languageId = Long.parseLong(languageIdString);
        	req.getSession().setAttribute("language", languageIdString);
            
            String sourceCode = req.getParameter("sourceCode");
            
            ContestProblemEntry contestProblemEntry;
           	contestProblemEntry = ContestProblemsModel.getEntry(problemId);
            if (null == contestProblemEntry)
            {
            	setRedirect("submit.jsp");
            	setMessage("Unknown problem");
            	return;
            }
            
            LanguageEntry language = LanguagesModel.getEntry(languageId);
            if (null == language)
            {
            	setRedirect("submit.jsp");
            	setMessage("Unknown language");
            	return;
            
            }
            
            ContestEntry contest = ContestsModel.getEntry(contestProblemEntry.getContestId());
            if (!contest.isAdmin(user))
            {
            	if (!contest.isStarted(user))
            	{
            		setRedirect("monitor.jsp?contest_id=" + contest.getId());
            		setMessage("Contest not started yet");
            		return;
            	}
            	if (contest.isFinished(user))
            	{
            		setRedirect("monitor.jsp?contest_id=" + contest.getId());
            		setMessage("Contest has finished");
            		return;
            	}
                Map<String, Object> map = new HashMap<String, Object>();
    			map.put("userId", user.getId());
    			map.put("contestProblemId", contestProblemEntry.getId());
    			map.put("active", true);
    			map.put("deleted", false);
    			map.put("flagFirstTestOnly", false);
    			
    			List<SubmissionEntry> list = SubmissionsModel.getSubmissions(map);
            	if (list.size() >= 5)
            	{
                    setMessage("Ви використали всі спроби для даної задачі");
                    setRedirect("olymp2011/submissions.jsp");
            		return;
            	}
            }
            
            ContestUserEntry contestUserEntry = ContestUsersModel.getOrCreateEntry(contest.getId(), user.getId());
            if (!contestUserEntry.canSubmit())
            {
                setMessage("Users with role `board' cannot submit solutions");
                return;
            }
            if (contestUserEntry.getStartTime() == null)
            {
            	contestUserEntry.setStartTime(new Date());
            	// TODO: fixme
            	//contestUserEntry.setCountdownTime(contest.getVirtual() ? new Date() : contest.getStartTime());
            }
            contestUserEntry.makePersistent();
            
            String senderInfo = req.getRemoteAddr();
            */
		/*	String id = SubmissionsModel.insertNew(user.getId(),
					contestProblemEntry.getId(), language.getId(), sourceCode,
					null != fFirstTestOnly, senderInfo);
            
            setMessage("Розв'язок прийнято, ID=" + id);
            setRedirect("contests/submissions.jsp?contest_id=" + contest.getId()); */
		/*}
        else
        {
        	UserEntry user = UsersModel.getCurrentUser(req);
        	if (null == user || !user.isAdmin())
        		return;
			if ("rejudge".equals(action))
			{
				SubmissionEntry se = null;//SubmissionsModel.getSubmission(req.getParameter("id"));
				if (se != null)
				{
					se.setDjudgeFlag(0);
					se.makePersistent();
				}
				if (null == returnToUrl)
					returnToUrl = "admin/submissions.jsp";
			}
			else if ("customEdit".equalsIgnoreCase(action))
			{
				//String id = req.getParameter("id");
				SubmissionEntry s = SubmissionsModel.getSubmission(id);
				if (null == s)
					return;
				ContestEntry contest = ContestsModel.getEntry(s.getContestId());
				ContestUserEntry cu = ContestUsersModel.getEntry(contest.getId(), user.getId());
				if (!cu.isJudge())
					return;
				
				int djudgeFlag = Integer.parseInt(req.getParameter("DjudgeFlag"));
				boolean fFlagFirstTestOnly = null != req.getParameter("FlagFirstTestOnly");
				boolean fVirtual = null != req.getParameter("Virtual");
				boolean fActive = null != req.getParameter("Active");
				String judgement = req.getParameter("Judgement");
				int maxMemoryUsed = Integer.parseInt(req.getParameter("MaxMemoryUsed"));
				int maxTimeUsed = Integer.parseInt(req.getParameter("MaxTimeUsed"));
				int score = Integer.parseInt(req.getParameter("Score"));
				int wrongTestNumber = Integer.parseInt(req.getParameter("WrongTestNumber"));
				
	        	boolean fEditAll = null != req.getParameter("EditAll");
	        	
	        	if (fEditAll || null != req.getParameter("EditScore"))
	        		s.setScore(score);
	        	if (fEditAll || null != req.getParameter("EditMaxTimeUsed"))
	        		s.setMaxTimeUsed(maxTimeUsed);
	        	if (fEditAll || null != req.getParameter("EditWrongTestNumber"))
	        		s.setWrongTestNumber(wrongTestNumber);
	        	if (fEditAll || null != req.getParameter("EditFlagFirstTestOnly"))
	        		s.setFlagFirstTestOnly(fFlagFirstTestOnly);
	        	if (fEditAll || null != req.getParameter("EditVirtual"))
	        		s.setVirtual(fVirtual);
	        	if (fEditAll || null != req.getParameter("EditActive"))
	        		s.setActive(fActive);
	        	if (fEditAll || null != req.getParameter("MaxMemoryUsed"))
	        		s.setMaxMemoryUsed(maxMemoryUsed);
	        	if (fEditAll || null != req.getParameter("EditJudgement"))
	        		s.setJudgement(judgement);
	        	if (fEditAll || null != req.getParameter("EditDjudgeFlag"))
	        		s.setDjudgeFlag(djudgeFlag);
	        	
	        	s.makePersistent();
	        	
	        	if (returnToUrl == null)
	        		returnToUrl = Linker.link("contests/admin/submission.jsp?contest_id=" + s.getContestId() + "&submission_id=" + id);
	        }
        }*/
	}

	@Override
	protected boolean processEdit(HttpServletRequest req, HttpServletResponse resp)
	{
		// TODO Auto-generated method stub
		return false;
	}
}
